/*global Aredis */

const errors = require('@feathersjs/errors')

// 更新最新权限到缓存
const upToRedis = (d) => {
  const rs = d.result
  if (d.method !== 'find') rs._id = rs._id.toString()
  if (d.method === 'remove') {
    return Aredis.hdel('roles', rs._id)
  } else if (['update', 'patch', 'create'].indexOf(d.method) !== -1){
    // Adebug.log('update role')
    if (rs.del === true) return Aredis.hdel('roles', rs._id)
    delete rs.del
    delete rs.__v
    Aredis.hset('roles', rs._id, JSON.stringify(rs))
  }
}

module.exports = {
  before: {
    all: [],
    find: [],
    get: [],
    create: [ d=> {
      let post = d.data
      let error
      let codes = ['name', 'powers']
      let zhrr = ['角色名称', '权限']
      codes.forEach((v, i)=> {
        if (error) return
        if (!post[v]) return error = new errors.BadRequest('请输入' + zhrr[i], {param: v})
        // if (rules[v]) error = rules[v](post)
      })
      if (error) return Promise.reject(error)
    }],
    update: [],
    patch: [],
    remove: []
  },

  after: {
    all: [upToRedis],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
}
